package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.dto.DeviceDataListDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.DeviceDataListByDayVo;
import com.zzyl.nursing.vo.DeviceDataListByWeekVo;
import com.zzyl.nursing.vo.DeviceHealthVo;
import com.zzyl.nursing.vo.QueryServiceVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-27
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void insertAmqpData(String contentStr) {
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        Object object = jsonObject.get("notify_data");

        //1.解析数据
        IotMsgNotifyData iotMsgNotifyData = BeanUtil.toBean(object, IotMsgNotifyData.class);
        //2.设备id 查询数据库
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new QueryWrapper<Device>().eq("iot_id", deviceId));
        if (device == null) {
            throw new RuntimeException("设备不存在");
        }
        //3.数据对象进行分析，获取properties map 数据循环插入到数据库
        iotMsgNotifyData.getBody().getServices().forEach(service -> {

            List<DeviceData> deviceDataList = new ArrayList<>();

            service.getProperties().forEach((key, value) -> {

                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setIotId(deviceId);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(String.valueOf(value));
                //处理上报时间日期
                LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                deviceData.setAlarmTime(alarmTime);
                deviceData.setId(null);
                deviceDataList.add(deviceData);
            });
            this.saveBatch(deviceDataList);

            //把插入到数据库的数据，同时放入到redis 中
            redisTemplate.opsForHash().put("iot:device_data", deviceId, JSONUtil.toJsonStr(deviceDataList));
        });

    }

    /**
     * 查询健康数据
     *
     * @param iotId
     * @return
     */
    @Autowired
    private IotClientConfig iotClientConfig;

    @Override
    public AjaxResult queryServiceProperties(String iotId) {
//    从iot平台获取设备影子数据
//        IoTDAClient client = iotClientConfig.huaWeiIotInstance();
//        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
//        request.withDeviceId(iotId);
//        ShowDeviceShadowResponse response = null;
//        try {
//            response = client.showDeviceShadow(request);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        List<DeviceShadowData> shadow = response.getShadow();
//        if (ObjectUtils.isEmpty(shadow)) {
//            return AjaxResult.success();
//        }
//        List<QueryServiceVo> queryServiceVoList = new ArrayList<>();
//        DeviceShadowData shadowData = shadow.get(0);
//
//        JSONObject jsonObject = JSONUtil.parseObj(shadowData.getReported().getProperties());
//        String eventTime = shadowData.getReported().getEventTime();
//        LocalDateTime time = null;
//        if (!ObjectUtils.isEmpty(eventTime)) {
//
//            LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
//            //日期时区转换
//            time = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
//                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
//                    .toLocalDateTime();
//        }
//        for (Map.Entry<String, Object> entry : jsonObject) {
//            QueryServiceVo vo = new QueryServiceVo();
//            vo.setFunctionId(entry.getKey());
//            vo.setValue(entry.getValue());
//            vo.setEventTime(time);
//            queryServiceVoList.add(vo);
//        }
//        return AjaxResult.success(queryServiceVoList);

//从数据库获取
//        根据iot和functionId查询设备数据，通过FunctionId分组实现去重，获取最新数据
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.lambdaQuery(DeviceData.class)
                .eq(DeviceData::getIotId, iotId)
                .select(DeviceData::getFunctionId, DeviceData::getAlarmTime, DeviceData::getDataValue)
                .groupBy(DeviceData::getFunctionId));
        List<DeviceHealthVo> deviceHealthVoList = new ArrayList<>();
//        封装vo
        for (DeviceData deviceData : deviceDataList) {
            DeviceHealthVo deviceHealthVo = new DeviceHealthVo();
            deviceHealthVo.setFunctionId(deviceData.getFunctionId());
            deviceHealthVo.setEventTime(deviceData.getAlarmTime());
            deviceHealthVo.setValue(deviceData.getDataValue());
            deviceHealthVoList.add(deviceHealthVo);
        }
        return AjaxResult.success(deviceHealthVoList);
    }

    /**
     * 按天统计查询指标数据
     *
     * @param deviceDataListByDayDto
     * @return
     */
    @Override
    public AjaxResult queryDeviceDataListByDay(DeviceDataListDto deviceDataListByDayDto) {
        //转换时间Long->LocalDateTime
        LocalDateTime start = LocalDateTimeUtil.of(deviceDataListByDayDto.getStartTime());
        LocalDateTime end = LocalDateTimeUtil.of(deviceDataListByDayDto.getEndTime());

        // 查询时间段内所有数据
        //最初想要每小时查询一次数据库，但是数据量太大，出现了内存溢出，
        // 改为查询时间段内的所有数据，在业务层中进行数据处理

        List<DeviceData> allData = this.list(
                Wrappers.lambdaQuery(DeviceData.class)
                        .between(DeviceData::getAlarmTime, start, end)
                        .eq(DeviceData::getIotId, deviceDataListByDayDto.getIotId())
                        .eq(DeviceData::getFunctionId, deviceDataListByDayDto.getFunctionId())
                        .select(DeviceData::getAlarmTime, DeviceData::getDataValue)
                        .orderByDesc(DeviceData::getAlarmTime)
        );

        // 把List<DeviceData>转成Map<小时, DeviceData>
        Map<Integer, DeviceData> latestPerHour = allData.stream()
                .collect(Collectors.toMap(
                        d -> d.getAlarmTime().getHour(),
                        d -> d,
                        //只保留最新一条
                        (a, b) -> a.getAlarmTime().isAfter(b.getAlarmTime()) ? a : b
                ));

        // 构造VO
        List<DeviceDataListByDayVo> voList = new ArrayList<>();
        for (int hour = 0; hour < 24; hour++) {
            DeviceDataListByDayVo vo = new DeviceDataListByDayVo();
            //格式化时间 "00:00" ~ "23:00"
            vo.setDateTime(String.format("%02d:00", hour));
            //判断该小时有无数据
            if (latestPerHour.containsKey(hour)) {
                vo.setDataValue(latestPerHour.get(hour).getDataValue());
            } else {
                // 没有数据时填 0
                vo.setDataValue("0.0");
            }

            voList.add(vo);
        }

        return AjaxResult.success(voList);
    }

    /**
     * 按周统计查询指标数据
     *
     * @param deviceDataListByDayDto
     * @return
     */
    @Override
    public AjaxResult queryDeviceDataListByWeek(DeviceDataListDto deviceDataListByDayDto) {

        LocalDate start = LocalDateTimeUtil.of(deviceDataListByDayDto.getStartTime()).toLocalDate();
        LocalDate end = LocalDateTimeUtil.of(deviceDataListByDayDto.getEndTime()).toLocalDate();

        // 查询数据库（示例：取每天最新一条）
        List<DeviceData> allData = this.list(
                Wrappers.lambdaQuery(DeviceData.class)
                        .between(DeviceData::getAlarmTime, start.atStartOfDay(), end.atTime(LocalTime.MAX))
                        .eq(DeviceData::getIotId, deviceDataListByDayDto.getIotId())
                        .eq(DeviceData::getFunctionId, deviceDataListByDayDto.getFunctionId())
                        .select(DeviceData::getAlarmTime, DeviceData::getDataValue)
                        .orderByDesc(DeviceData::getAlarmTime)
        );

        // 转成 Map<日期, DeviceData>，每天只保留最新一条
        Map<LocalDate, DeviceData> latestPerDay = allData.stream()
                .collect(Collectors.toMap(
                        d -> d.getAlarmTime().toLocalDate(),
                        d -> d,
                        //如果同一小时有多条数据，比较时间，保留 alarmTime更晚的数据
                        (a, b) -> a.getAlarmTime().isAfter(b.getAlarmTime()) ? a : b
                ));

        //  构造一周7天的VO
        List<DeviceDataListByDayVo> voList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            LocalDate day = start.plusDays(i);
            DeviceDataListByDayVo vo = new DeviceDataListByDayVo();
            vo.setDateTime(day.format(DateTimeFormatter.ofPattern("MM.dd")));
            vo.setDataValue(latestPerDay.containsKey(day) ? latestPerDay.get(day).getDataValue() : "0.0");
            voList.add(vo);
        }

        return AjaxResult.success(voList);
    }


}
